//
//  UpdateAddressControllerViewController.m
//  CenturyInterconnection
//
//  Created by Tian Wei You on 16/4/26.
//  Copyright © 2016年 Shanghai DuRui Information Technology Company. All rights reserved.
//

#import "UpdateAddressControllerViewController.h"
#import "CountryViewController.h"
#import "MyTextField.h"


@interface UpdateAddressControllerViewController ()<UITextFieldDelegate,CountryViewControllerDelegate>

@property(nonatomic,strong)UIScrollView * scrollView;

//@property(nonatomic,strong)UITableView*tableView;

@property(nonatomic,assign)BOOL canSave;    //判断是否符合

@property(nonatomic,strong)UITextField *firstNameText;
@property(nonatomic,strong)UITextField *lastNameText;
@property(nonatomic,strong)UITextField *streetAddressText;
@property(nonatomic,strong)UITextField *postCodeText;
@property(nonatomic,strong)UITextField *cityText;
@property(nonatomic,strong)UITextField *stateText;
@property(nonatomic,strong)UILabel *countryLabel;

@property(nonatomic,strong)UITextField *telephoneText;

@property(nonatomic,strong)NSDictionary *countryDic;
@property(nonatomic,strong)NSString *countryStr;

@end

@implementation UpdateAddressControllerViewController




- (void)viewDidLoad {
    [super viewDidLoad];
    
    _firstNameText=[[UITextField alloc]init];
    _firstNameText.delegate=self;
    _lastNameText=[[UITextField alloc]init];
    _lastNameText.delegate=self;
    _streetAddressText=[[UITextField alloc]init];
    _streetAddressText.delegate=self;
    _postCodeText=[[UITextField alloc]init];
    _postCodeText.delegate=self;
    _cityText=[[UITextField alloc]init];
    _cityText.delegate=self;
    _stateText=[[UITextField alloc]init];
    _stateText.delegate=self;
    _telephoneText=[[UITextField alloc]init];
    _telephoneText.delegate=self;
    _countryLabel=[[UILabel alloc]init];
    
    _countryDic=[[NSDictionary alloc]init];
    
    _canSave=NO;
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
    self.scrollView.frame = CGRectMake(0, 0, KScreenWidth, KScreenHeight);
    [self.view addSubview:self.scrollView];
   
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    [self makeNaviButton];
    
    [self addMainView];
    
    [self addView];
    
    [self getDatas];
    
    
    //[self.view addSubview:self.tableView];
    
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tapGr.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGr];

}

-(void)getDatas{
    
    //http://viprunningonline.com/api/index.php? main_page=countries
    
    NSString*urlStr=[NSString stringWithFormat:@"%@",HTTP_ADDRESS];
    NSDictionary*params=@{@"main_page":@"countries"};
    HttpManager*manager=[[HttpManager alloc]init];
    [manager getDataFromNetworkWithUrl:urlStr parameters:params compliation:^(id data, NSError *error) {
        
        NSString*number=[NSString stringWithFormat:@"%@",data[@"status"]];
        
        if ([number isEqualToString:@"1"]) {
            self.countryDic=data[@"data"][@"countries"];
        }
    }];
    
}

-(void)makeNaviButton{
    
    self.title=@"UPDATE ADDRESS";
    
    UIButton *forkButton=[[UIButton alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(320), 0, ACTUAL_WIDTH(30), ACTUAL_HEIGHT(30))];
    [forkButton setImage:[UIImage imageNamed:@"nav_close"] forState:0];
    [forkButton addTarget:self action:@selector(comeBackToRoot) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"nav_back"] forState:0];
    leftButton.frame=CGRectMake(0, 0, ACTUAL_WIDTH(23), ACTUAL_HEIGHT(23));
    [leftButton addTarget:self action:@selector(comeBack) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    UIBarButtonItem*item1 = [[UIBarButtonItem alloc]initWithCustomView:forkButton];
    
    UIBarButtonItem*item= [[UIBarButtonItem alloc]initWithCustomView:leftButton];
    
    self.navigationItem.leftBarButtonItem=item;
    
    self.navigationItem.rightBarButtonItem=item1;
    
}


#pragma mark - 返回事件

-(void)comeBackToRoot{
    [UserSession instance].isGotoPayment=NO;
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}

-(void)comeBack{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)addMainView{

    //1
    _firstNameText = [MyTextField TextField:@"FIRSTNAME:"];
    [_firstNameText  setOrigin:CGPointMake(20, 10)];
    self.firstNameText.delegate = self;
    [self.scrollView addSubview:_firstNameText];
    
    
    //2
    _lastNameText = [MyTextField TextField:@"LASTNAME:"];
    [_lastNameText setOrigin:CGPointMake(20, 64)];
    self.lastNameText.delegate = self;
    [self.scrollView addSubview:_lastNameText];

    
    //3
    UITextField *label7=[[UITextField alloc] init];
    label7.frame = CGRectMake(20, 128, 100 , 44);
    label7.placeholder=@"COUNTRY:";
    label7.textColor = [UIColor blackColor];
    label7.font = FONT_SYSTEM_32;
    [self.scrollView addSubview:label7];

    _countryLabel.frame=CGRectMake(120, 128, KScreenWidth-110, 44);
    _countryLabel.tag=3;
    _countryLabel.font = FONT_SYSTEM_32;
    [self.scrollView addSubview:_countryLabel];

    UIButton *selectCountryButton=[[UIButton alloc]initWithFrame:CGRectMake(0, 128, KScreenWidth, 44)];
    [selectCountryButton addTarget:self action:@selector(gotoCountryAndSelect) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:selectCountryButton];

    
    //4
    _stateText = [MyTextField TextField:@"STATE:"];
    [_stateText setOrigin:CGPointMake(20, 182)];
    self.stateText.delegate = self;
    [self.scrollView addSubview:_stateText];

    //5
    _cityText = [MyTextField TextField:@"CITY:"];
    [_cityText setOrigin:CGPointMake(20, 236)];
    self.cityText.tag = 5;
    self.cityText.delegate = self;
    [self.scrollView addSubview:_cityText];

    //UIButton *selectStateButton=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, ACTUAL_HEIGHT(60))];
    //[selectStateButton addTarget:self action:@selector(gotoCityAndSelect) forControlEvents:UIControlEventTouchUpInside];
    //[BGView addSubview:selectStateButton];

    //6
    _postCodeText = [MyTextField TextField:@"POSTCODE:"];
    [_postCodeText setOrigin:CGPointMake(20, 290)];
    self.postCodeText.delegate = self;
    self.postCodeText.tag = 6;
    [self.scrollView addSubview:_postCodeText];

    //8  新增电话控件
    _telephoneText = [MyTextField TextField:@"TELEPHONE:"];
    [_telephoneText setOrigin:CGPointMake(20, 344)];
    self.telephoneText.delegate = self;
    self.telephoneText.tag = 8;
    [self.scrollView addSubview:_telephoneText];

    //7
    _streetAddressText = [MyTextField TextField:@"STREET ADDRESS:"];
    _streetAddressText.delegate = self;
    _streetAddressText.tag = 7;
    [_streetAddressText setOrigin:CGPointMake(20, 398)];
    [self.scrollView addSubview:_streetAddressText];

}

-(void)addView{
    
//    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 500, KScreenWidth, 300)];
//    bgView.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1];
//    [self.view addSubview:bgView];
    
    UIButton *button = [[ UIButton alloc] initWithFrame:CGRectMake(10, KScreenHeight-50, KScreenWidth-20, 44)];
    button.tag=333;
    button.backgroundColor = [UIColor colorWithRed:0.12 green:0.13 blue:0.13 alpha:1];
    [button setTitle:@"UPDATE" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(UpdateAndComeBack:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
//    UIView *whiteView=[[UIView alloc]initWithFrame:CGRectMake(0, 600, KScreenWidth, KScreenHeight-600)];
//    whiteView.backgroundColor=[UIColor whiteColor];
//    [self.view addSubview:whiteView];
    
}



#pragma mark - 跳转页面选择国家并且返回数据
-(void)gotoCountryAndSelect{
    CountryViewController *vc=[[CountryViewController alloc]init];
    vc.delegate=self;
    [self.navigationController pushViewController:vc animated:YES];
}

//pragma mark "国家选择"界面的代理委托
//-(void)delegateForBack0:(NSString *)str0{
//    self.countryLabel.text=str0;
//}
-(void)delegateForBack0:(NSString *)str0 And:(NSString *)str1{
    self.countryLabel.text=str0;
    self.countryStr=str1;
}

#pragma mark - gotoStateAndSelect
- (void)gotoStateAndSelect
{
    if (self.countryStr) {
        //跳转到州
        
        
    }else{
        [JRToast showWithText:@"Please choose a state." duration:2.0];
    }
}


#pragma mark - gotoCityAndSelect
- (void)gotoCityAndSelect
{
    
}


#pragma mark Update按钮点击事件

-(void)UpdateAndComeBack:(UIButton*)sender{
//    int countryID=[self.countryStr intValue];
    if (sender.selected==YES) {
        return;
    }else{
        sender.selected=YES;
        [self performSelector:@selector(timeEnough:) withObject:nil afterDelay:2.0];
        NSString*str=[self judgeCansave];

        if (_canSave) {
            
            // http://viprunningonline.com/api/index.php?  main_page=address_book_process
            
            NSString*aaa=@"main_page=address_book_process";
            NSString*urlStr=[NSString stringWithFormat:@"%@%@",HTTP_ADDRESS,aaa];
            
            NSDictionary*params=@{@"act":@"add",
                                  @"firstname":self.firstNameText.text,
                                  @"lastname":self.lastNameText.text,
                                  @"street_address":self.streetAddressText.text,
                                  @"postcode":self.postCodeText.text,
                                  @"city":self.cityText.text,
                                  @"state":self.stateText.text,
                                  @"zone_country_id":self.countryStr,
                                  @"customers_telephone":self.telephoneText.text,
                                  @"zenid":[UserSession instance].cookie};
            HttpManager*manager=[[HttpManager alloc]init];
            
            [manager postDataFromNetworkWithUrl:urlStr parameters:params compliation:^(id data, NSError *error) {
                
                NSString*number=[NSString stringWithFormat:@"%@",data[@"status"]];
                
                if ([number isEqualToString:@"1"]) {
                    [JRToast showWithText:@"Shipping address fill out successfully！"];
                    [self comeBack];
                    [self returnTheData];
                }else{
                    [JRToast showWithText:data[@"status_message"]];
                }
            }];

        }else{
            [JRToast showWithText:str duration:2.0];
        }
    }
}
#pragma mark 返回数据
-(void)returnTheData{
    if ([self.delegate respondsToSelector:@selector(delegateForBack)]) {
        [self.delegate delegateForBack];
    }
}

#pragma mark 未填写警告

-(NSString*)judgeCansave{
    _canSave=YES;
    _countryStr=self.countryDic[self.countryLabel.text];
    
    if (_firstNameText.text.length==0) {
        _canSave=NO;
        return @"Last name cannot be empty！";
    }
    if (_lastNameText.text.length==0) {
        _canSave=NO;
        return @"The name cannot be empty！";
    }
    if (_streetAddressText.text.length==0) {
        _canSave=NO;
        return @"Address cannot be empty！";
    }
    if (_postCodeText.text.length==0) {
        _canSave=NO;
        return @"Zip code cannot be empty！";
    }
    if (_telephoneText.text.length==0) {
        _canSave=NO;
        return @"Telephone number cannot be empty！";
    }
    if (_cityText.text.length==0) {
        _canSave=NO;
        return @"City cannot be empty！";
    }
    if (_stateText.text.length==0) {
        _canSave=NO;
        return @"Provinces and cities cannot be empty！";
    }
    
    if (_countryLabel.text.length==0) {
        _canSave=NO;
        return @"Countries cannot be empty！";
    }
    
    if (_countryStr==nil) {
        _canSave=NO;
        return @"This country cannot be found！";
    }
    return @"666";
}


- (UIView*)findFirstResponderBeneathView:(UIView*)view
{
    // Search recursively for first responder
    for ( UIView *childView in view.subviews ) {
        if ( [childView respondsToSelector:@selector(isFirstResponder)] && [childView isFirstResponder] )
            return childView;
        UIView *result = [self findFirstResponderBeneathView:childView];
        if ( result )
            return result;
    }
    return nil;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [[self findFirstResponderBeneathView:self.view] resignFirstResponder];
    
}

-(void)timeEnough:(NSTimer*)timer{
    UIButton *btn=(UIButton*)[self.view viewWithTag:333];
    btn.selected=NO;
    [timer invalidate];
    timer=nil;
}

//touch began
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [[self findFirstResponderBeneathView:self.view] resignFirstResponder];
}

#pragma mark - textFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [[self findFirstResponderBeneathView:self.view] resignFirstResponder];
    [textField resignFirstResponder];
    

    return YES;
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (textField.tag == 5 || textField.tag == 6 || textField.tag == 7 || textField.tag == 8) {
        [UIView animateWithDuration:0.25 animations:^{
//            [self.tableView setY:self.tableView.y-70];
            [self.scrollView setY:self.scrollView.y-150];
        }];

    }
    return YES;
}

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    if (textField.tag == 5 || textField.tag == 6 || textField.tag == 7 || textField.tag == 8) {
    [UIView animateWithDuration:0.25 animations:^{
//        [self.tableView setY:self.tableView.y+70];
        [self.scrollView setY:self.scrollView.y+150];
    }];
    }
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
    if ([text isEqualToString:@"\n"]) {
        
        [textField resignFirstResponder];
        return NO;
    }
    
    return YES;
}

#pragma mark 键盘收回

-(void)viewTapped:(UITapGestureRecognizer*)tapGr
{
    [self.view endEditing:YES];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
